<template>
  <a-drawer
    title="修改楼盘信息"
    :maskClosable="false"
    width=650
    placement="right"
    :closable="false"
    @close="onClose"
    :visible="userEditVisiable"
    style="height: calc(100% - 55px);overflow: auto;padding-bottom: 53px;">

    <a-form :form="form">
      <a-form-item label='楼盘名称' v-bind="formItemLayout">
        <a-input v-decorator="[
        'estateName',
        { rules: [{ required: true, message: '请输入楼盘名称!' }] }
        ]"/>
      </a-form-item>
      <a-form-item label='楼盘概述' v-bind="formItemLayout">
        <a-input v-decorator="[
        'estateContent',
        { rules: [{ required: true, message: '请输入楼盘概述!' }] }
        ]"/>
      </a-form-item>
      <a-form-item label='项目配套' v-bind="formItemLayout">
        <a-input v-decorator="[
        'matchs'
        ]"/>
      </a-form-item>
      <a-form-item label='楼盘类型' v-bind="formItemLayout">
        <a-select v-decorator="[
        'estateType'
        ]">
          <a-select-option value="0">热销楼盘</a-select-option>
          <a-select-option value="1">新盘预告</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='地理位置' v-bind="formItemLayout">
        <a-input v-decorator="[
        'address'
        ]"/>
      </a-form-item>
      <a-form-item label='参考价格' v-bind="formItemLayout">
        <a-input v-decorator="[
        'referencePrice'
        ]"/>
      </a-form-item>
      <a-form-item label='开盘时间' v-bind="formItemLayout">
        <a-date-picker v-decorator="[
        'openTime'
        ]"/>
      </a-form-item>
      <a-form-item label='联系电话' v-bind="formItemLayout">
        <a-input v-decorator="[
        'contactNumber'
        ]"/>
      </a-form-item>
      <a-form-item label='主力户型' v-bind="formItemLayout">
        <a-input v-decorator="[
        'mainTyoe'
        ]"/>
      </a-form-item>
      <a-form-item label='物业类别' v-bind="formItemLayout">
        <a-select v-decorator="[
        'propertyType'
        ]">
          <a-select-option value="0">高层</a-select-option>
          <a-select-option value="1">住宅</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='物业管理费' v-bind="formItemLayout">
        <a-input v-decorator="[
        'propertyPrice'
        ]"/>
      </a-form-item>
      <a-form-item label='物业公司' v-bind="formItemLayout">
        <a-input v-decorator="[
        'conpanyProperty'
        ]"/>
      </a-form-item>
      <a-form-item label='建筑类型' v-bind="formItemLayout">
        <a-select v-decorator="[
        'buildingType'
        ]">
          <a-select-option value="0">别墅 洋房</a-select-option>
          <a-select-option value="1">高层</a-select-option>
          <a-select-option value="2">平层住宅</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='装修状态' v-bind="formItemLayout">
        <a-select v-decorator="[
        'decorationStatus'
        ]">
          <a-select-option value="0">精装</a-select-option>
          <a-select-option value="1">简装</a-select-option>
          <a-select-option value="2">轻奢</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='项目状态' v-bind="formItemLayout">
        <a-select v-decorator="[
        'projectStatus'
        ]">
          <a-select-option value="0">在售</a-select-option>
          <a-select-option value="1">未开售</a-select-option>
          <a-select-option value="2">已售完</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label='户型区间' v-bind="formItemLayout">
        <a-input v-decorator="[
        'intervalUnit'
        ]"/>
      </a-form-item>
      <a-form-item label='产权年限' v-bind="formItemLayout">
        <a-input v-decorator="[
        'propertyRight'
        ]"/>
      </a-form-item>
      <a-form-item label='楼层状况' v-bind="formItemLayout">
        <a-input v-decorator="[
        'floor'
        ]"/>
      </a-form-item>
      <!--      <a-form-item label='户型图' v-bind="formItemLayout">-->
      <!--        <a-upload-->
      <!--          name="avatar"-->
      <!--          list-type="picture-card"-->
      <!--          class="avatar-uploader"-->
      <!--          :show-upload-list="false"-->
      <!--          action="http://localhost:9527/web/fileUpload"-->
      <!--          @change="imgHandleChange1"-->
      <!--          :before-upload="beforeUpload"-->
      <!--        >-->
      <!--          <img v-if="img.imgUrl1" :src="img.imgUrl1" alt="avatar" style="width: 200px;height: 200px;"/>-->
      <!--          <div v-else>-->
      <!--            <a-icon :type="loadingImg ? 'loading' : 'plus'" />-->
      <!--            <div class="ant-upload-text">-->
      <!--              Upload-->
      <!--            </div>-->
      <!--          </div>-->
      <!--        </a-upload>-->
      <!--      </a-form-item>-->
      <a-form-item label='样板房图片' v-bind="formItemLayout">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://localhost:9527/web/fileUpload"
          @change="imgHandleChange2"
          :before-upload="beforeUpload"
        >
          <img v-if="img.imgUrl2" :src="img.imgUrl2" alt="avatar" style="width: 200px;height: 200px;"/>
          <div v-else>
            <a-icon :type="loadingImg ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label='园林景观' v-bind="formItemLayout">
        <a-upload
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="http://localhost:9527/web/fileUpload"
          @change="imgHandleChange3"
          :before-upload="beforeUpload"
        >
          <img v-if="img.imgUrl3" :src="img.imgUrl3" alt="avatar" style="width: 200px;height: 200px;"/>
          <div v-else>
            <a-icon :type="loadingImg ? 'loading' : 'plus'" />
            <div class="ant-upload-text">
              Upload
            </div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label='地址' v-bind="formItemLayout">
        <a-input style="width: 70%" v-decorator="[
        'address'
        ]"/>
        <a-button type="primary" style="width: 30%" @click="showChildrenDrawer">
          选择地址
        </a-button>
      </a-form-item>

    </a-form>
    <drawerMap :childrenDrawerShow="childrenDrawer" @handlerClosed="handlerClosed"></drawerMap>

    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">提交</a-button>
    </div>
  </a-drawer>
</template>
<script>
  import drawerMap from '@/utils/map/searchmap/drawerMap'
  import baiduMap from '@/utils/map/baiduMap'
  import {mapState, mapMutations} from 'vuex'
  import dayjs from 'dayjs'

  const formItemLayout = {
    labelCol: {span: 3},
    wrapperCol: {span: 18}
  }
  export default {
    name: 'UserEdit',
    props: {
      userEditVisiable: {
        default: false
      }
    },
    components: {
      drawerMap
    },
    data() {
      return {
        loadingImg: false,
        // 别怪我这样写 太鸡儿ex
        img: {
          imgUrl1: '',
          imgName1: '',
          imgUrl2: '',
          imgName2: '',
          imgUrl3: '',
          imgName3: '',
        },
        childrenDrawer: false,
        localPoint: '',
        formItemLayout,
        account: {},
        form: this.$form.createForm(this),
        deptTreeData: [],
        keychecks: [],
        roleData: [],
        menuKeys: [],
        userDept: [],
        mockData: [],
        targetKeys: [],
        appInfoData: [],
        roleInfoData: [],
        roleKeys: [],
        orgInfoData: [],
        menuInfoData: [],
        userId: '',
        loading: false
      }
    },
    computed: {
      ...mapState({
        currentUser: state => state.account.user
      })
    },
    created() {
      //this.getMock();
      // this.getAppInfo();
      // this.getRoleInfo();
      // this.getMenuInfoByTree();
    },
    methods: {
      ...mapMutations({
        setUser: 'account/setUser'
      }),
      handlerClosed(localPoint) {
        this.childrenDrawer = false
        if(localPoint !=null && localPoint != undefined) {
          this.localPoint = localPoint;
          let address = baiduMap.getAddress(localPoint);
          address.getLocation(localPoint, (rs) => {
            if(rs != null) {
              if(rs.address != undefined && rs.address.length != 0) {
                this.stayAddress = rs.address;
              }
              if(rs.surroundingPois != undefined) {
                if(rs.surroundingPois.address != undefined && rs.surroundingPois.address.length != 0) {
                  this.stayAddress = rs.surroundingPois.address;
                }
              }

              this.form.getFieldDecorator("address")
              let obj = {}
              obj["address"] = this.stayAddress
              this.form.setFieldsValue(obj)

            }
          });
        }
      },
      showChildrenDrawer() {
        this.childrenDrawer = true;
      },
      getBase64(img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
      },
      imgHandleChange1(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl1 = imageUrl;
            this.img.imgName1 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      imgHandleChange2(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl2 = imageUrl;
            this.img.imgName2 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      imgHandleChange3(info) {
        if (info.file.status === 'uploading') {
          this.loadingImg = true;
          return;
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.getBase64(info.file.originFileObj, imageUrl => {
            this.img.imgUrl3 = imageUrl;
            this.img.imgName3 = info.file.response;
            this.loadingImg = false;
          });
        }
      },
      beforeUpload(file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          this.$message.error('You can only upload JPG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
      },
      onClose() {
        this.loading = false
        this.form.resetFields()
        this.$emit('close')
      },
      setFormValues({...user}) {
        this.userId = user.id
        let fields = ['estateName', 'estateContent','matchs','estateType','address','referencePrice','openTime','contactNumber','mainTyoe','propertyType','propertyPrice','conpanyProperty','buildingType','decorationStatus','projectStatus','intervalUnit','propertyRight','floor']
        Object.keys(user).forEach((key) => {
          if(key === "floorImg") {
            this.img.imgUrl1 = "/static/img/image/"+user["floorImg"].toString()
            this.img.imgName1 = user["floorImg"].toString()
          }
          if(key === "sampleImg") {
            this.img.imgUrl2 = "/static/img/image/"+user["sampleImg"].toString()
            this.img.imgName2 = user["sampleImg"].toString()
          }
          if(key === "scenicImg") {
            this.img.imgUrl3 = "/static/img/image/"+user["scenicImg"].toString()
            this.img.imgName3 = user["scenicImg"].toString()
          }
          if(key === "estateType") {
            user["estateType"] = user["estateType"].toString()
          }
          if(key === "propertyType") {
            user["propertyType"] = user["propertyType"].toString()
          }
          if(key === "buildingType") {
            user["buildingType"] = user["buildingType"].toString()
          }
          if(key === "projectStatus") {
            user["projectStatus"] = user["projectStatus"].toString()
          }
          if(key === "decorationStatus") {
            user["decorationStatus"] = user["decorationStatus"].toString()
          }
          if(key === "point") {
            if(user["point"] !== null && user["point"] !== "") {
              this.localPoint = JSON.parse(user["point"])
            }
          }
          if (fields.indexOf(key) !== -1) {
            if(key === "sex") {
              user["sex"]=user["sex"].toString()
            }
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = user[key]
            this.form.setFieldsValue(obj)
          }
        })
      },
      onDeptChange(value) {
        this.userDept = value
      },
      handleSubmit() {
        this.form.validateFields((err, values) => {
          if (!err) {
            this.loading = true
            let user = this.form.getFieldsValue()
            user.point = JSON.stringify(this.localPoint)
            user.floorImg = this.img.imgName1
            user.sampleImg = this.img.imgName2
            user.scenicImg = this.img.imgName3
            user.openTime = dayjs(user.openTime).format('YYYY-MM-DD')
            user.id = this.userId;
            this.$put('/cos/estate-info', {
              ...user
            }).then((r) => {
              this.loading = false
              this.$emit('success')
            }).catch(() => {
              this.loading = false
            })
          }
        })
      },
      filterOption(inputValue, option) {
        return option.description.indexOf(inputValue) > -1;
      },
      handleChange(targetKeys, direction, moveKeys) {
        console.log(targetKeys, direction, moveKeys);
        this.targetKeys = targetKeys;
      },
      handleChanges(targetKeys, direction, moveKeys) {
        this.roleKeys = targetKeys;
      },
      handleSearch(dir, value) {
        console.log('search:', dir, value);
      },
      onSelect(keys) {
        this.menuKeys = keys,
          console.log('Trigger Select', keys);
      },
      onCheck(checkedKeys, e) {
        console.log(JSON.stringify(checkedKeys));
      },
    },
    watch: {
      userEditVisiable() {
        if (this.userEditVisiable) {
          this.$get('role').then((r) => {
            this.roleData = r.data.rows
          })
          this.$get('dept').then((r) => {
            this.deptTreeData = r.data.rows.children
          })
        }
      }
    }
  }
</script>
